/*
 * Copyright (C), 2002-2017, 上海亦寻信息技术有限公司
 * FileName: LevelStaticSalesDataServiceFacadeImpl.java
 * Author:   linyao
 * Date:     2017-3-8 下午2:39:34
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.emm.yixun.system.service.impl.pmo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.CodeTypeEnum;
import com.emm.yixun.system.service.pmo.PmoStaticDataServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.emm.yixun.basic.service.BaseCodeTypeService;
import com.emm.yixun.basic.service.BaseCodeValueService;
import com.emm.yixun.basic.service.PmoLogService;
import com.emm.yixun.basic.service.ProjectInfoService;
import com.emm.yixun.basic.service.ProjectPmoService;
import com.emm.yixun.basic.service.ProjectPremisesIndustDataService;
import com.emm.yixun.basic.service.ProjectPremisesIndustDataVersionService;
import com.emm.yixun.basic.service.ProjectPremisesInfoService;
import com.emm.yixun.basic.service.ProjectPremisesPmoService;
import com.emm.yixun.basic.service.ProjectPremisesService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.common.enums.IndustMarkEnums;
import com.emm.yixun.common.enums.LevelEnums;
import com.emm.yixun.common.model.BaseCodeType;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.LevelStaticSalesData;
import com.emm.yixun.common.model.LevelStaticSalesDataChild;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectInfo;
import com.emm.yixun.common.model.ProjectPmo;
import com.emm.yixun.common.model.ProjectPremises;
import com.emm.yixun.common.model.ProjectPremisesIndustData;
import com.emm.yixun.common.model.ProjectPremisesIndustDataVersion;
import com.emm.yixun.common.model.ProjectPremisesInfo;
import com.emm.yixun.common.model.ProjectPremisesPmo;
import com.emm.yixun.common.model.StaticSalesData;
import com.emm.yixun.common.model.StaticSalesFieldIndustData;
import com.emm.yixun.common.model.StaticSalesIndustData;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.pmo.TargetAveragePrice;
import com.emm.yixun.common.model.pmo.TargetPriceOfParkinSpace;
import com.emm.yixun.common.model.pmo.TargetValue;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.system.service.pmo.LevelStaticSalesDataServiceFacade;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 * 
 * @author linyao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service("levelStaticSalesDataFacade")
@WebService(name = "com.emm.yixun.system.service.pmo.LevelStaticSalesDataServiceFacade")
public class LevelStaticSalesDataServiceFacadeImpl implements LevelStaticSalesDataServiceFacade {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private PmoLogService pmoLogService;
	@Autowired
	private ProjectPmoService projectPmoService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private ProjectPremisesService premisesService;
	@Autowired
	private ProjectInfoService projectInfoService;
	@Autowired
	private ProjectPremisesPmoService projectPremisesPmoService;
	@Autowired
	private ProjectPremisesInfoService projectPremisesInfoService;
	@Autowired
	private ProjectPremisesIndustDataService projectPremisesIndustDataService;
	@Autowired
	private  ProjectPremisesIndustDataVersionService projectPremisesIndustDataVersionService;
	
	@Autowired
	private  BaseCodeValueService baseCodeValueService;
	
	@Autowired
	private BaseCodeTypeService baseCodeTypeService;
	@Autowired
	private PmoStaticDataServiceFacade pmoStaticDataServiceFacade;
	
	
	@Value("pmo.indust.parkIds")
	private String parkIds;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.system.service.pmo.LevelStaticSalesDataServiceFacade#updateProjectInfo(com.emm.yixun.common.model
	 * .LevelStaticSalesData)
	 */
	@Override
	public Response<LevelStaticSalesData> updateProjectInfo(Long merchantId, Long projectId,boolean isLog) {
		Response<LevelStaticSalesData> response = new Response<LevelStaticSalesData>();
		response.setSuccess(Boolean.FALSE);
		LevelStaticSalesData levelStaticSalesData = new LevelStaticSalesData();
		try {
			levelStaticSalesData.setLevel(LevelEnums.LEVELENUMS_PROJECT.getName());
			// 查询项目
			Project project = projectService.selectById(projectId);
			ProjectInfoDto projectInfoDto = new ProjectInfoDto();
			projectInfoDto.setProjectId(projectId);
			ProjectInfo projectInfo = projectInfoService.selectByDto(projectInfoDto);
			// 查询项目PMO
			StaticSalesData staticSalesData = new StaticSalesData();
			ProjectPmoDto projectPmoDto = new ProjectPmoDto();
			projectPmoDto.setProjectId(projectId);
			ProjectPmo projectPmo = projectPmoService.selectByDto(projectPmoDto);
			// 查询项目组团
			ProjectPremisesDto projectPremisesDto = new ProjectPremisesDto();
			projectPremisesDto.setProjectId(projectId);
			List<ProjectPremises> projectPremises = premisesService.selectListByDto(projectPremisesDto);
			if (projectPremises != null && projectPremises.size() > 0) {
				// 规证分期数
				levelStaticSalesData.setStageNumber(projectPremises.size());
			} else {
				// 规证分期数
				levelStaticSalesData.setStageNumber(0);
			}
			levelStaticSalesData.setProjectCode(projectPmo.getPmoProjectCode());
			if (null != projectPmo) {
				pmoStaticDataServiceFacade.buildProjectStaticData(staticSalesData, project, projectInfo, projectPmo);
			}
			// 项目静态销售数据
			levelStaticSalesData.setData(staticSalesData);

			// 下级静态销售数据列表(组团)
			List<LevelStaticSalesDataChild> staticSalesDatas = new ArrayList<LevelStaticSalesDataChild>();
			ProjectPremisesPmoDto premisesPmoDto = new ProjectPremisesPmoDto();
			premisesPmoDto.setProjectId(projectId);
			List<ProjectPremisesPmo> projectPremisesPmos = projectPremisesPmoService.selectListByDto(premisesPmoDto);
			if (projectPremisesPmos != null && projectPremisesPmos.size() > 0) {
				/**
				 * 项目下楼盘
				 */
				ProjectPremisesDto ppDto = new ProjectPremisesDto();
				ppDto.setProjectId(projectId);
				List<ProjectPremises> ppList = premisesService.selectListByDto(ppDto);
				Map<Long, ProjectPremises> ppMap = new HashMap<>();
				if(null != ppList && ppList.size() > 0){
					for(ProjectPremises pp: ppList){
						ppMap.put(pp.getId(), pp);
					}
				}
				/**
				 * 组团附加信息
				 */
				ProjectPremisesInfoDto ppiDto = new ProjectPremisesInfoDto();
				ppiDto.setProjectId(projectId);
				List<ProjectPremisesInfo> ppiList = projectPremisesInfoService.selectListByDto(ppiDto);
				Map<Long, ProjectPremisesInfo> ppiMap = new HashMap<>();
				if(null != ppiList && ppiList.size() > 0){
					for(ProjectPremisesInfo ppi: ppiList){
						ppiMap.put(ppi.getPremisesId(), ppi);
					}
				}

				for (ProjectPremisesPmo projectPremisesPmo : projectPremisesPmos) {
					List<StaticSalesIndustData> list = new ArrayList<StaticSalesIndustData>();
					LevelStaticSalesDataChild child = new LevelStaticSalesDataChild();
					// 组团表
					ProjectPremises premises = ppMap.get(projectPremisesPmo.getPremisesId());
					if(null==premises)continue;
					// 组团信息表
					ProjectPremisesInfo projectPremisesInfo = ppiMap.get(projectPremisesPmo.getPremisesId());
					StaticSalesData salesData = new StaticSalesData();
					child.setPremisesId(premises.getId());
					child.setProjectName(premises.getGroupName());
					child.setProjectCode(projectPremisesPmo.getPmoPremisesCode());
					child.setLevel(LevelEnums.LEVELENUMS_PHASESTAGING.getName());
					setStaticSalesData(salesData, projectPremisesPmo, premises, projectPremisesInfo, list);
					child.setData(salesData);
					staticSalesDatas.add(child);
				}
			}

			levelStaticSalesData.setStaticSalesDatas(staticSalesDatas);
			response.success(levelStaticSalesData);
		} catch (Exception e) {
			response.fail();
			response.setResultMessage("数据查询失败");
			logger.error("数据查询失败:{}", e);
		}finally{
			if(isLog && response.isSuccess()){
				String json = JSON.toJSONString(levelStaticSalesData);
				PmoLogDto pmoLogDto = new PmoLogDto();
				pmoLogDto.setMerchantId(merchantId);
				pmoLogDto.setDirection("1");
				pmoLogDto.setStatus("0");
				pmoLogDto.setRequestParams(json);
				pmoLogDto.setDelFlag("0");
				pmoLogDto.setInterfaceName("销售主数据");
				PmoLogDto logDto = pmoLogService.create(pmoLogDto);
				response.setResultMessage(logDto.getId().toString());
			}
			
			
		}
		return response;
	}
	/**
	 * 
	 * staticSalesIndustResult:项目级别业态数据 <br/>
	 * @author Administrator
	 * @param projectId
	 * @return
	 * @since JDK 1.6
	 */
	public List<StaticSalesIndustData> staticSalesIndustResult(Long projectId){
	    List<StaticSalesIndustData> array = new ArrayList<StaticSalesIndustData>();
	    ProjectPremisesIndustDataDto industDataDto = new ProjectPremisesIndustDataDto();
	    industDataDto.setProjectId(projectId);
	    industDataDto.setIndustType("0");
	    industDataDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
	    List<ProjectPremisesIndustData> projectPremisesIndustData =  projectPremisesIndustDataService.selectListByDto(industDataDto);
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
	    	Map<String, BaseCodeValueDto> bcvMap = baseCodeValueService.selectBcvMap(bcvDto);

			for (ProjectPremisesIndustData indust : projectPremisesIndustData) {
				StaticSalesIndustData industData = new StaticSalesIndustData();
				industData.setId(indust.getId());
				if(!StringUtils.isEmpty(indust.getIndustMark())){
					bcvDto =  bcvMap.get(indust.getIndustMark());
					if(bcvDto != null){ //小业态
						industData.setIndustKey(bcvDto.getCodeName());
						industData.setIndustMark(bcvDto.getCodeValue());
						//大业态
						industData.setIndustValue(bcvDto.getTypeName());
					}

					StaticSalesFieldIndustData salesField = new StaticSalesFieldIndustData();
					salesField.setGroundSalesAcreag(indust.getGroundSalesAcreag()==null?null:new Float(indust.getGroundSalesAcreag().toString()));
					salesField.setNumberOfBuildi(indust.getNumberOfBuildi());
					salesField.setNumberLayers(indust.getNumberLayers());
					salesField.setSalableAcreag(indust.getSalableAcreag()==null?null:new Float(indust.getSalableAcreag().toString()));
					salesField.setSelfSustaiAcreag(indust.getSelfSustaiAcreag()==null?null:new Float(indust.getSelfSustaiAcreag().toString()));
					salesField.setUndergSalesAcreag(indust.getUndergSalesAcreag()==null?null:new Float(indust.getUndergSalesAcreag().toString()));
					salesField.setTotalHouse(indust.getTotalHouse());
					salesField.setTargetValue(indust.getTargetValue());
					salesField.setTargetAveragPrice(indust.getTargetAveragPrice());
					ProjectPremisesIndustDataVersionDto versionDto = new ProjectPremisesIndustDataVersionDto();
					versionDto.setIndustId(indust.getId());
					versionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					versionDto.setOrders(" t.effect_start_time desc");
					List<ProjectPremisesIndustDataVersion> industDataList = projectPremisesIndustDataVersionService.selectListByDto(versionDto);
					if(null!=industDataList&&industDataList.size()>0){
						ProjectPremisesIndustDataVersion version = industDataList.get(0);
						salesField.setTargetVersionName(version.getVersionName());
					}
					industData.setIndustData(salesField);
				}
				array.add(industData);
			}

	    return array;
	}
	
	

	public void setStaticSalesData(StaticSalesData staticSalesData, ProjectPremisesPmo premisesPmo,
			ProjectPremises premises, ProjectPremisesInfo projectPremisesInfo, List<StaticSalesIndustData> list) {
		// 项目静态销售业态数据
		ProjectPremisesIndustDataDto entity = new ProjectPremisesIndustDataDto();
		entity.setPremisesId(premises.getId());
		entity.setIndustType("1"); //分期级的业态
		List<ProjectPremisesIndustData> listPPID=projectPremisesIndustDataService.selectListByDto(entity);
		if(null != listPPID && listPPID.size() > 0){
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
			Map<String, BaseCodeValueDto> bcvMap = baseCodeValueService.selectBcvMap(bcvDto);

			for(ProjectPremisesIndustData data : listPPID){
				String industMark = data.getIndustMark();
				if(StringUtils.isBlank(industMark)){
					continue;
				}
				//查询M2系统业态参数表
				bcvDto =  bcvMap.get(industMark);
				if(null == bcvDto){
					continue;
				}
				String pmoIndustMark = bcvDto.getCodeValue();
				StaticSalesIndustData staticSalesIndustData = new StaticSalesIndustData();
				staticSalesIndustData.setId(data.getId());
				staticSalesIndustData.setParentId(bcvDto.getTypeId());
				//大业态
				staticSalesIndustData.setIndustValue(bcvDto.getTypeName());
				//小业态
				staticSalesIndustData.setIndustKey(bcvDto.getCodeName());
				staticSalesIndustData.setIndustMark(pmoIndustMark);
				StaticSalesFieldIndustData industData = new StaticSalesFieldIndustData();
				//自持货值
				industData.setTargetValue(data.getTargetValue());
				industData.setTargetAveragPrice(data.getTargetAveragPrice());
				//如果业态是车位则只计算车位个数和自持面积
				if(pmoIndustMark.equals(IndustMarkEnums.INDUSTMARKENUMS_PARKINSPACE.getCode())){
					industData.setNumberOfParkinSpace(data.getSalableAcreag() == null ? null : data.getSalableAcreag().intValue());
				}else{
					industData.setGroundSalesAcreag(data.getGroundSalesAcreag() == null ? null : data.getGroundSalesAcreag().floatValue());
					industData.setNumberLayers(data.getNumberLayers());
					industData.setNumberOfBuildi(data.getNumberOfBuildi());
					industData.setSalableAcreag(data.getSalableAcreag() == null ? null : data.getSalableAcreag().floatValue());
					industData.setSelfSustaiAcreag(data.getSelfSustaiAcreag() == null ? null : data.getSelfSustaiAcreag().floatValue());
					industData.setTotalHouse(data.getTotalHouse());
					industData.setUndergSalesAcreag(data.getUndergSalesAcreag() == null ? null : data.getUndergSalesAcreag().floatValue());
				}
				//目标销售均价, 版本
			   	ProjectPremisesIndustDataVersionDto versionDto = new ProjectPremisesIndustDataVersionDto();
			   	versionDto.setIndustId(data.getId());
			   	versionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			   	versionDto.setOrders(" t.effect_start_time desc");
			   	List<ProjectPremisesIndustDataVersion> industDataList = projectPremisesIndustDataVersionService.selectListByDto(versionDto);
			   	if(null!=industDataList && industDataList.size()>0){
					ProjectPremisesIndustDataVersion version = industDataList.get(0);
					industData.setTargetVersionName(version.getVersionName());
			   	}
				staticSalesIndustData.setIndustData(industData);
				list.add(staticSalesIndustData);
			}
		}
       
		staticSalesData.setIndust(list);
		//分期的回款指标
		//staticSalesData.setPaymentTargetList(projectService);
		//分期的销售指标
		//staticSalesData.setSaleTargetList(saleTargetList);
		staticSalesData.setStaginName(premisesPmo.getStaginName());
		if(null!=projectPremisesInfo){
			// 总户数，单位：户
			staticSalesData.setTotalHouse(premises.getHouseholdsTotal());
			//栋数
			staticSalesData.setNumberOfBuildi(premisesPmo.getNumberOfBuildi());
			// 自持面积，单位：万平方米
			if(null!=projectPremisesInfo.getOwnArea()){
				staticSalesData.setSelfSustaiAcreag(projectPremisesInfo.getOwnArea().floatValue());
			}

			// 可售面积，单位：万平方米
			if(null!=projectPremisesInfo.getHousingArea()){
				staticSalesData.setSalableAcreag(projectPremisesInfo.getHousingArea().floatValue());
			}
			//地上可售面积，单位：万平方米
			if(null!=projectPremisesInfo.getGroundArea()){
			   staticSalesData.setGroundSalesAcreag(projectPremisesInfo.getGroundArea().floatValue());
			}

			//地下可售面积，单位：万平方米
			if(null!=projectPremisesInfo.getUndergroundArea()){
			   staticSalesData.setUndergSalesAcreag(projectPremisesInfo.getUndergroundArea().floatValue());
			}

			// 地下停车场面积，单位：万平方米
			staticSalesData.setUndergParkinAcreag(projectPremisesInfo.getUndergroundParkingArea() == null ? null
					: projectPremisesInfo.getUndergroundParkingArea().floatValue() / 10000);
			// 地下停车场数量，单位：个
			staticSalesData.setUndergParkinLot(projectPremisesInfo.getUndergroundParkingNum());
			// 地上机动车位，单位：个
			staticSalesData.setGroundVechicParkinSpace(projectPremisesInfo.getGroundMotor());
			// 地下机动车位，单位：个
			staticSalesData.setUndergVechicParkinSpace(projectPremisesInfo.getUndergroundMotor());
			// 地上非机动车位，单位：个
			staticSalesData.setGroundNonVechicParkinSpace(projectPremisesInfo.getGroundNonMotor());
			// 地下非机动车位，单位：个
			staticSalesData.setUndergNonVechicParkinSpace(projectPremisesInfo.getUndergroundNonMotor());
		}
		// 车位数，单位：个
		staticSalesData.setNumberOfParkinSpace(premises.getCarportTotal());
		// 赠送面积，单位：平方米
		staticSalesData.setPresenAcreag(premisesPmo.getPresenAcreag() == null ? null : premisesPmo.getPresenAcreag()
				.floatValue());
		// 可售套数，单位：套
		staticSalesData.setSalableNumber(premisesPmo.getSalableNumber());
		//组团级别目标销售均价、车位均价、目标货值
		initNewList(staticSalesData,premisesPmo);
	}
	
	private void initNewList(StaticSalesData staticSalesData,ProjectPremisesPmo premisesPmo){
		//目标销售均价、车位均价、目标货值
		List<TargetAveragePrice> targetAveragePriceList=new ArrayList<TargetAveragePrice>();
		List<TargetPriceOfParkinSpace> targetPriceOfParkinSpaceList=new ArrayList<TargetPriceOfParkinSpace>();
		List<TargetValue> targetValueList=new ArrayList<TargetValue>();
		//车位目标销售均价
		TargetPriceOfParkinSpace tpops=new TargetPriceOfParkinSpace();
		if(null!=premisesPmo.getTargetPriceOfParkinVersion())
		    tpops.setTargetPriceOfParkinVersion(premisesPmo.getTargetPriceOfParkinVersion());
		if(null!=premisesPmo.getTargetPriceOfParkinSpaceTime())
		    tpops.setEffectStartTime(DateUtils.DateToString(premisesPmo.getTargetPriceOfParkinSpaceTime(), DateStyle.YYYYMMDD));
		if(null!=premisesPmo.getTargetPriceOfParkinSpace())
		    tpops.setTargetPriceOfParkinSpace(premisesPmo.getTargetPriceOfParkinSpace().floatValue());
		    targetPriceOfParkinSpaceList.add(tpops);
		
		//目标销售均价
		TargetAveragePrice tap=new TargetAveragePrice();
		if(null!=premisesPmo.getTargetAveragPriceVersion())
			tap.setTargetAveragPriceVersion(premisesPmo.getTargetAveragPriceVersion());
		if(null!=premisesPmo.getTargetAveragPriceTime())
			tap.setEffectStartTime(DateUtils.DateToString(premisesPmo.getTargetAveragPriceTime(), DateStyle.YYYYMMDD));
		if(null!=premisesPmo.getTargetAveragPrice())
			tap.setTargetAveragPrice(premisesPmo.getTargetAveragPrice().floatValue());
		targetAveragePriceList.add(tap);
		//目标货值
		TargetValue tv=new TargetValue();
		if(null!=premisesPmo.getTargetValueVersion())
			tv.setTargetValueVersion(premisesPmo.getTargetValueVersion());
		if(null!=premisesPmo.getTargetValueTime())
		    tv.setEffectStartTime(DateUtils.DateToString(premisesPmo.getTargetValueTime(), DateStyle.YYYYMMDD));
		if(null!=premisesPmo.getTargetValue())
			tv.setTargetValue(premisesPmo.getTargetValue().floatValue());
		targetValueList.add(tv);
		
		
		// 目标销售均价，单位：万元;销售软件增加字段，目标销售均价为目标货值版本的均价。
		staticSalesData.setTargetAveragPrice(targetAveragePriceList);
		// 车位目标销售均价,单位：万元。
		staticSalesData.setTargetPriceOfParkinSpace(targetPriceOfParkinSpaceList);
		// 目标货值，单位：万元。
		staticSalesData.setTargetValue(targetValueList);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.emm.yixun.system.service.pmo.LevelStaticSalesDataServiceFacade#updatePmoLog(java.lang.Long)
	 */
	@Override
	public Response<Boolean> updatePmoLog(PmoLogDto entity) {
		Response<Boolean> response = new Response<Boolean>();
		response.setEntity(Boolean.FALSE);
		try {
			response.setEntity(Boolean.TRUE);
			pmoLogService.update(entity);
		} catch (Exception e) {
			logger.error("更新日志失败,logId：{}", entity.getId());
		}
		return response;
	}

	public String getParkIds() {
		return parkIds;
	}

	public void setParkIds(String parkIds) {
		this.parkIds = parkIds;
	}
	
}
